package com.warrior.superdata.service.impl;

import com.warrior.superdata.dds.DataSourceHelp;
import com.warrior.superdata.enums.DatasourceType;
import com.warrior.superdata.enums.OperateType;
import com.warrior.superdata.mysql.entity.dto.ApiInfoDetailDto;
import com.warrior.superdata.service.DeleteSqlService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @ClassName: EsDeleteServiceImpl.java
 * @date: 2022/6/28 14:29
 * @author xujian
 */
@Service
@Slf4j
public class EsDeleteServiceImpl implements DeleteSqlService {

    @Autowired
    private DataSourceHelp dataSourceHelp;

    @Override
    public String getDatasourceType() {
        return DatasourceType.ES.getName();
    }

    @Override
    public String getOperateType() {
        return OperateType.DELETE.getName();
    }

    @Override
    public Object execute(ApiInfoDetailDto apiInfoDetailDto) {
        Long result = 0l;
        try {
            DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(apiInfoDetailDto.getMainTableName());
            BoolQueryBuilder boolQueryBuilder = EsQueryHelpService.generateQuery(apiInfoDetailDto.getParams());
            deleteByQueryRequest.setQuery(boolQueryBuilder);
            BulkByScrollResponse bulkByScrollResponse = dataSourceHelp.getRestHighLevelClient(apiInfoDetailDto.getDatasourceDto()).
                    deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
            result = bulkByScrollResponse.getTotal();
        } catch (Exception e) {
            log.error("es delete异常 errMsg:{}", e.getMessage());
        }
        return result;
    }
}
